<?php

namespace app\admin\controller;

use app\admin\model\SstalinkDevice;
use app\common\controller\Backend;

use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\Session;
use think\Validate;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Sensor extends Backend
{
    
    /**
     * SstalinkSensor模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('SstalinkSensor');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        $ids=$this->request->param("ids");
        $admin = Session::get("admin");
        if($ids==NULL)
            $devices = SstalinkDevice::all(["ownerid" => $admin->id]);
        else
            $devices=[SstalinkDevice::get(["deviceid" => $ids])];
        if ($this->request->isAjax()) {
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            $deviceids = "";
            $devicePair = array();
            foreach ($devices as $key => $device) {
                $devicePair[$device->deviceid] = $device->name;
                $deviceids .= $device->deviceid . ',';
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where("deviceid","in",$deviceids)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where("deviceid","<>","")
                ->where("deviceid","in",$deviceids)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key => $value){
                $value->deviceid = $devicePair[$value->deviceid]."(".$value->deviceid.")";
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        if($ids!=NULL){
            $deviceInfo=$devices[0]->name."(".$devices[0]->deviceid.")";
        }else{
            $deviceInfo="所有设备";
        }
        $this->view->assign("device",$deviceInfo);
        return $this->view->fetch();
    }

    public function add(){
        $ids=$this->request->param("ids");
        $admin=Session::get("admin");
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $showtype=$this->request->post("show/a");
            if($showtype){
                $params["showtype"]=json_encode($showtype);
            }
            $hooklist="";
            $hooks= $this->request->post("hook/a");
            if($hooks){
                foreach ($hooks as $k => &$v) {
                    $v=base64_encode($v);
                }
                $hooklist=implode(',',$hooks);
            }
            $params['hooklist']=$hooklist;
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params["createtime"]=date("Y-m-d H:i:s" ,time());
                    $params["modifytime"]=$params["createtime"];
                    $params['updatetime']=$params["createtime"];
                    $result = $this->model->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $datalist="";$deviceout="";
        $devices=SstalinkDevice::all(["ownerid" => $admin->id]);
        foreach ($devices as $key => $device){
            if($device->deviceid==$ids){
                $deviceout=$device->deviceid;
            }
            $datalist .= "<option value='".$device->deviceid."'>".$device->name."(".$device->deviceid.")"."</option>";
        }
        $this->view->assign("datalist",$datalist);
        $this->view->assign("deviceout",$deviceout);
        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        $admin=Session::get("admin");
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $showtype=$this->request->post("show/a");
            if($showtype){
                $params["showtype"]=json_encode($showtype);
            }
            if ($params) {
                foreach ($params as $k => &$v) {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                $hooklist="";
                $hooks= $this->request->post("hook/a");
                if($hooks){
                    foreach ($hooks as $k => &$v) {
                        $v=base64_encode($v);
                    }
                    $hooklist=implode(',',$hooks);
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $params["hooklist"]=$hooklist;
                    $params["updatetime"]=date("Y-m-d H:i:s" ,time());
                    $result = $row->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $temp=SstalinkDevice::get(["deviceid" => $row->deviceid]);
        $datalist = "<option value='".$row->deviceid."'>".$temp->name."(".$temp->deviceid.")"."</option>";
        $devices=SstalinkDevice::all(["ownerid" => $admin->id]);

        foreach ($devices as $key => $device){
            if($device->deviceid!=$row->deviceid)
                $datalist .= "<option value='".$device->deviceid."'>".$device->name."(".$device->deviceid.")"."</option>";
        }

        $this->view->assign("datalist",$datalist);
        $hooklist=explode(",",$row->hooklist);
        foreach ($hooklist as $k => $v){
            $hooklist[$k]=base64_decode($v);
        }
        $this->view->assign("hooklist",$hooklist);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds)->delete($ids);
            }
            else
            {
                $count = $this->model->destroy($ids);
            }
            if ($count)
            {
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
